package com.sufen.seckill.utils;

/**
 * @Author sufen
 * @Date 2021/10/23 12:04
 * @Version 1.0
 * 功能描述：生成1000个用户的工具类
 */
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sufen.seckill.pojo.User;
import com.sufen.seckill.vo.RespBean;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserUtil {
   private static void createUser(int count) throws Exception {
      List<User> users = new ArrayList<>(count);
      //生成用户
      for (int i = 0; i < count; i++) {
         User user = new User();
         user.setId(13000000000L + i);
         user.setLoginCount(1);
         user.setNickname("user" + i);
         user.setRegisterDate(new Date());
         user.setSalt("1a2b3c4d");
         user.setPassword(MD5UTIL.inputPassToDBPass("123456", user.getSalt()));
         users.add(user);
     }
//      System.out.println("create user");
//      //插入数据库
//       //拿一个数据库连接，已配置好，命名为conn。
//      Connection conn = getConn();
//      //写一个sql语句
//      String sql = "insert into t_user(login_count, nickname, register_date, salt, password, id)values(?,?,?,?,?,?)";
//      //把这个sql语句扔进conn里，用preparedstatement跑，后面要手动传参。↓
//      PreparedStatement pstmt = conn.prepareStatement(sql);
//      for (int i = 0; i < users.size(); i++) {
//         User user = users.get(i);
//         pstmt.setInt(1, user.getLoginCount());
//         pstmt.setString(2, user.getNickname());
//         pstmt.setTimestamp(3, new Timestamp(user.getRegisterDate().getTime()));
//         pstmt.setString(4, user.getSalt());
//         pstmt.setString(5, user.getPassword());
//         pstmt.setLong(6, user.getId());
//         pstmt.addBatch();
//     }
//      //传参结束，这个conn已经能执行批量且参数传好了的sql语句了。
//      pstmt.executeBatch();
//      //执行结束了，关闭掉prestatement和conn。
//      pstmt.close();
//      conn.close();
//      //到此为止已经把生成的user，即用户ID和Password传进了mysql里面了。
//      System.out.println("insert to db");
      //登录，生成token
      String urlString = "http://localhost:8080/login/doLogin";
      //搞一个文件来接收登陆后用户的Cookie。
      File file = new File("C:\\Users\\sufen\\Desktop\\java\\安装包\\JMeter脚本\\1k的用户Cookie.txt");
      if (file.exists()) {
         file.delete();
     }
      RandomAccessFile raf = new RandomAccessFile(file, "rw");
      file.createNewFile();
      raf.seek(0);
      //这里就是把生成的手机号，即user的id和password，放进网站的login页面里面跑，
       // 然后取出Cookie，存user的id和Cookie的对应关系行。
       //其中，Cookie就是userTicket，可以在返回的respBean里面通过把ticket传到obj那个参数取到。
      for (int i = 0; i < users.size(); i++) {
         User user = users.get(i);
         URL url = new URL(urlString);
         HttpURLConnection co = (HttpURLConnection) url.openConnection();
         co.setRequestMethod("POST");
         co.setDoOutput(true);
         OutputStream out = co.getOutputStream();
         String params = "mobile=" + user.getId() + "&password=" + MD5UTIL.inputPassToFromPass("123456");
         out.write(params.getBytes());
         out.flush();
         InputStream inputStream = co.getInputStream();
         ByteArrayOutputStream bout = new ByteArrayOutputStream();
         byte buff[] = new byte[1024];
         int len = 0;
         while ((len = inputStream.read(buff)) >= 0) {
            bout.write(buff, 0, len);
         }
         inputStream.close();
         bout.close();
         String response = new String(bout.toByteArray());
         ObjectMapper mapper = new ObjectMapper();
         RespBean respBean = mapper.readValue(response, RespBean.class);
         //从respbean里面拿到ticket，即Cookie
         String userTicket = ((String) respBean.getObj());
         System.out.println("create userTicket : " + user.getId());
         //获得手机号（user的id和Cookie的对应关系）
         String row = user.getId() + "," + userTicket;
         raf.seek(raf.length());
         raf.write(row.getBytes());
         raf.write("\r\n".getBytes());
         System.out.println("write to file : " + user.getId());
     }
      raf.close();
      System.out.println("over");
   }
   private static Connection getConn() throws Exception {
      String url = "jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
      String username = "root";
      String password = "123456";
      String driver = "com.mysql.cj.jdbc.Driver";
      Class.forName(driver);
      return DriverManager.getConnection(url, username, password);
   }
   public static void main(String[] args) throws Exception {
      createUser(5000);
   }
}